<?php

namespace C\S\Coupon;

use C\L\Service;
use C\M\Coupons;
use C\M\CouponReceive as CouponReceiveModel;

class CouponReceive extends Service
{

    protected function setModel()
    {
        $this->model = new \C\M\CouponReceive();
    }

    public function getStatusConfig()
    {
        return [
            'coupon_usage_status' => [
                'N' => '未使用',
                'Y' => '已使用',
                'D' => '已过期',
            ]
        ];
    }

    /**
     * 代金券领取
     */
    public function couponReceiveCreate($arr)
    {
        if (!isset($arr['uid'])) {
            throw new \Exception('uid不能为空');
        }
        if (!isset($arr['coupon_id'])) {
            throw new \Exception('券id不能为空');
        }

        $coupon_info = $this->di['s_coupon']->search(['id' => $arr['coupon_id']]);
        if (!$coupon_info) {
            throw new \Exception('代金券不存在');
        }

        if (empty($arr['effective_time'])) {
            $arr['effective_time'] = $coupon_info['effective_time'];
            if (empty($arr['effective_time'])) {
                throw new \Exception('effective_time为空');
            }
        }
        // 检测是否重复领取
        if ($this->search(['uid' => $arr['uid'], 'coupon_id' => $arr['coupon_id']])) {
            throw new \Exception("重复领取");
        }
        $add = [];
        $add['uid'] = $arr['uid'];
        $add['type'] = '2';
        $add['coupon_id'] = $arr['coupon_id'];
        $add['num'] = isset($arr['num']) ? $arr['num'] : '1';
        $time = time();
        $add['stime'] = $time;
        $add['etime'] = $time + (86400 * $arr['effective_time']);
        return $this->save($add);
    }

    /**
     * 返回某用户当前可用代金券的列表
     */
    public function voucherList($uid, $receiveIds = [], $usedIds = [])
    {
        // $list = $this->searchAll([
        //     'uid' => $uid,
        //     'type' => '2',
        //     'status' => 'N',
        //     'status' => 'N',
        // ],[
        //     'uid' => '=',
        //     'type' => '=',
        //     'status' => '=',
        //     'status' => '=',
        // ]);
        $conditions = '';
        if (!empty($usedIds)) {
            $usedIds = implode(',', $usedIds);
            $conditions = " AND id not in ($usedIds)";
        }
        $list = $this->model->find("uid = $uid AND type in (2,3,4) AND status = 'N'".$conditions)->toArray();
        if (empty($list)) {
            return $list;
        }
        foreach ($list as $key => &$value) {
            $coupon_info = $this->di['s_coupon']->search(['id' => $value['coupon_id']]);
            $value['coupon_value'] = $coupon_info['coupon_value'] ?? '';
            if (in_array($value['id'], $receiveIds)) {
                $value['coupon_value_sort'] = $value['coupon_value'] + 10000; //选中的优惠券排在前面
            } else {
                $value['coupon_value_sort'] = $value['coupon_value'];
            }
            $value['coupon_type'] = $coupon_info['coupon_type'] ?? '';
            $value['use_condition'] = $coupon_info['use_condition'] ?? '';
            $value['use_condition_msg'] = $coupon_info['use_condition_msg'] ?? '';
        }
        return $this->sortByMultiCols($list, ['coupon_value_sort' => 'SORT_DESC']);
    }

    public function sortByMultiCols($rowset, $args)
    {
        $sortArray = array();
        $sortRule = '';
        foreach ($args as $sortField => $sortDir) {
            foreach ($rowset as $offset => $row) {
                $sortArray[$sortField][$offset] = $row[$sortField];
            }
            $sortRule .= '$sortArray[\'' . $sortField . '\'], ' . $sortDir . ', ';
        }
        if (empty($sortArray) || empty($sortRule)) {
            return $rowset;
        }
        eval('array_multisort(' . $sortRule . '$rowset);');
        return $rowset;
    }

    /**
     * 代金券核销处理
     * $id @ coupon_receive表 自增id
     */
    public function voucherVerifiNum($uid, $id)
    {
        $receive = $this->search(['id' => $id, 'uid' => $uid]);
        if (empty($receive)) {
            throw new \Exception("未领取该券");
        }
        // 订单提交前校验代金券是否过期
        $curr_minute = date('YmdHi');
        $end_minute = date('YmdHi', $receive['etime']);
        if ($curr_minute >= $end_minute) {
            throw new \Exception("优惠券已过期，请刷新后重新操作");
        }
        $u_res = $this->update($id, ['status' => 'Y']);
        if (!$u_res) {
            throw new \Exception("更新coupon_receive表失败");
        }
        // 核销数+1
        return $this->di['s_coupon']->verifiNum($receive['coupon_id']);
    }

    public function availableCoupons($userId, $amount)
    {
        return CouponReceiveModel::availableCoupons($userId, $amount);
    }
}
